package com.example.myapplication.activity;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.example.myapplication.R;
import com.example.myapplication.bean.LinearAdapter;
import com.example.myapplication.bean.MessageReceived;
import com.example.myapplication.bean.MyWebSocketClient;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
public class activity_chat extends AppCompatActivity {
    //服务器地址
    //URI uri = URI.create("ws://121.36.92.128:8084//websocket");
    private EditText mChatInputEditText;
    private List<MessageReceived> messageList;
    private WebSocketClient socketClient;

    private Button back;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        //去除默认标题栏
        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }

        //获取userid
        SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        String username = sp.getString("loginUserName", "default");
        String picture = sp.getString("picture","default");

        // 获取组件引用
        mChatInputEditText = findViewById(R.id.chatInputEditText);
        Button mSendButton = findViewById(R.id.sendButton);
        //Button mPrivateButton = findViewById(R.id.privateButton);
        RecyclerView mrv = findViewById(R.id.messageRecyclerView);
        back = (Button) findViewById(R.id.tv_back);

        //连接适配器
        messageList = new ArrayList<>();//初始化数据列表
        LinearAdapter linearAdapter = new LinearAdapter(messageList,activity_chat.this);
        mrv.setAdapter(linearAdapter);

        //创建websocketclient实例
        socketClient = new MyWebSocketClient(username){
            @Override
            public void onMessage(String message) {
                // 接收到消息时执行的操作
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            MessageReceived messageReceived = new MessageReceived(message,username);
                            //如果时聊天消息类型
                                messageList.add(messageReceived);
                                // 通知适配器数据集已更改，刷新 RecyclerView
                                linearAdapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
            }
        };

        ReadyState readyState = socketClient.getReadyState();
//
        //当WebSocket的状态是NOT_YET_CONNECTED时使用connect()方法进行初始化开启链接：
        if (readyState == ReadyState.NOT_YET_CONNECTED ) {
            Log.i("WebSocket", "---初始化WebSocket客户端---");
        //连接服务器
            try {
                socketClient.connectBlocking();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }


        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                activity_chat.this.finish();
            }
        });

        //设置私聊按钮点击事件监听器
//        mPrivateButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent1=new Intent(activity_chat.this,activity_privateChat.class);
//                startActivity(intent1);
//            }
//        });
        // 设置聊天输入框的点击事件监听器
        mChatInputEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 请求焦点
                mChatInputEditText.setFocusableInTouchMode(true);
                mChatInputEditText.requestFocus();

                // 显示键盘
                InputMethodManager inputMethodManager =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(mChatInputEditText, 0);
            }
        });

        // 设置发送按钮的点击事件监听器
        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取文本输入框中的消息内容
                String message = mChatInputEditText.getText().toString();

                JSONObject json = new JSONObject();
                try {
                    json.put("message", message);
                    json.put("username",username);
                    json.put("type", "群发");
                    json.put("tousername","");
                    json.put("picture",picture);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                socketClient.send(json.toString());
                // 清空文本输入框
                mChatInputEditText.setText("");
            }
        });
    }
}